//修改信息的抽屉
import { useEffect, useState } from 'react'
import { AtForm, AtImagePicker, AtInput } from 'taro-ui'
import Taro from '@tarojs/taro'
import { putAvatarService, userPutService } from '@/api/user'
import { useDispatch } from 'react-redux'
import { SET_USER } from '@/constants'
import Styles from './index.module.scss'

function EditUserInfo(props) {
  const dispatch = useDispatch()
  const [nickname, setNickname] = useState<string>('')
  const [avatar, setAvatar] = useState<string>('')
  const [phone, setPhone] = useState<string>('')
  const [realName, setRealName] = useState<string>('')
  const [sex, setSex] = useState<string>('')
  const [files, setFiles] = useState<any>([])
  const [showAdd, setShowAdd] = useState<boolean>()

  const handleChooseImage = (selectedFiles) => {
    setFiles(selectedFiles)
    //限制只能选择一张图片
    if (selectedFiles.length === 1) {
      setFiles(selectedFiles.slice(0, 1))
      setAvatar(selectedFiles[0].url)
      //上传图片后不允许继续添加
      setShowAdd(false)
    } else {
      //删除唯一图片后展示上传
      setShowAdd(true)
      setFiles([])
    }
  }

  useEffect(() => {
    console.log('查看是否存下图片信息', files)
  }, [files])

  const handleSubmit = async () => {
    if (
      avatar === '' &&
      nickname === '' &&
      sex === '' &&
      realName === '' &&
      phone === '' &&
      files.length === 0
    ) {
      Taro.showToast({
        title: '您未修改任何信息！',
        icon: 'none',
      })
      return
    }

    //上传图片获取url
    try {
      const res = await putAvatarService(files[0])
      console.log('上传图片结果:', res)
      if (res.code === 0) {
        //保存头像到仓库
        dispatch({ type: SET_USER, payload: { avatar: res.data.url } })
        Taro.showToast({
          title: '上传成功',
          icon: 'none',
        })
        setAvatar(res.data.url)
      }
    } catch (err) {
      Taro.showToast({
        title: '上传图片失败',
        icon: 'none',
      })
    }

    // 处理提交逻辑
    try {
      const res = await userPutService({
        avatar: avatar,
        name: realName,
        nickName: nickname,
        phone: phone,
        sex: sex,
      })
      if (res.code === 0) {
        Taro.showToast({
          title: '提交成功',
          icon: 'none',
        })
        // //成功后保存用户信息到仓库
        // dispatch({
        //   type: SET_USER,
        //   payload: {
        //     avatar: avatar,
        //     realName: realName,
        //     nickname: nickname,
        //     phone: phone,
        //     sex: sex,
        //   },
        // })
        //修改成功收起修改面板
        props.controlDrawerShow()
        //提醒父组件刷新用户数据
        props.getUserInfo()
      } else {
        Taro.showToast({
          title: res.msg,
          icon: 'none',
        })
      }
    } catch {
      Taro.showToast({
        title: '提交失败',
        icon: 'none',
      })
    }
  }

  useEffect(() => {
    // 获取用户信息
  })

  return (
    <AtForm className={Styles.edit_user_info}>
      <div className={Styles.drawer}>
        <div className={Styles.drawer_container}>
          <div className={Styles.drawer_items}>
            {(props.action === 1 || props.action === 6) && (
              <div className={Styles.avatar}>
                <div className={Styles.word1}>
                  <span className={Styles.word_span}>修改头像:</span>
                </div>

                <AtImagePicker
                  length={2}
                  files={files}
                  showAddBtn={showAdd}
                  onChange={handleChooseImage}
                />
              </div>
            )}
            {(props.action === 2 || props.action === 6) && (
              <div className={Styles.item}>
                <span className={Styles.word}>修改昵称：</span>
                <AtInput
                  style={{ height: '50px' }}
                  name='nickname'
                  title='昵称'
                  type='text'
                  placeholder='请输入您的昵称'
                  value={nickname}
                  onChange={(value: string) => setNickname(value)}
                />
              </div>
            )}
            {(props.action === 3 || props.action === 6) && (
              <div className={Styles.item}>
                <span className={Styles.word}>修改性别：</span>
                <AtInput
                  name='sex'
                  title='性别'
                  type='text'
                  placeholder='男/女'
                  value={sex}
                  onChange={(value: string) => setSex(value)}
                />
              </div>
            )}

            {(props.action === 4 || props.action === 6) && (
              <div className={Styles.item}>
                <span className={Styles.word}>绑定姓名：</span>
                <AtInput
                  name='realName'
                  title='姓名'
                  type='text'
                  placeholder='请输入您的名字'
                  value={realName}
                  onChange={(value: string) => setRealName(value)}
                />
              </div>
            )}

            {(props.action === 5 || props.action === 6) && (
              <div className={Styles.item}>
                <span className={Styles.word}>绑定手机号：</span>
                <AtInput
                  name='phone'
                  title='手机号'
                  type='number'
                  placeholder='请输入您的手机号'
                  value={phone}
                  onChange={(value: string) => setPhone(value)}
                />
              </div>
            )}
          </div>
          <div className={Styles.btn}>
            <div>
              <button className={Styles.submit_button} onClick={handleSubmit}>
                提交
              </button>
            </div>
            <div>
              <button
                className={Styles.submit_button}
                onClick={props.controlDrawerShow}
              >
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
    </AtForm>
  )
}

export default EditUserInfo
